package tianqi.controller.shop;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tianqi.entity.Addr;
import tianqi.entity.UserY;
import tianqi.service.shop.impl.BalanceServiceImpl;
import tianqi.service.shop.impl.ShopCarServiceImpl;

@Controller
public class BalanceController {
	
	@Autowired
	private ShopCarServiceImpl shopCarServiceImpl;
	
	@Autowired
	private BalanceServiceImpl balanceServiceImpl;
	
	/**
	 * 在用户点击结算时，判断用户是否为登录状态
	 * @param res
	 * @return
	 */
	@RequestMapping("/isLogin")
	@ResponseBody
	public String isLogin(HttpServletRequest res){
		UserY user = (UserY) res.getSession().getAttribute("user");
		return user==null?"false":"true";
	}
	
	/**
	 * 在提交订单页中，显示购物车中的商品信息
	 * @param req
	 * @param res
	 * @param m
	 * @return
	 */
	@RequestMapping("/orderConfirm")
	public String orderConfirm(HttpServletRequest req, HttpServletResponse res, Model m){
		UserY userY=(UserY) req.getSession().getAttribute("user");
		if (userY == null) {
			return "redirect:show.tq";
		}
		List<Addr> queryAddrByUid = balanceServiceImpl.queryAddrByUid(userY);
		m.addAttribute("addrs", queryAddrByUid);
		
		shopCarServiceImpl.queryCar(req, res, m);
		return "orderConfirm";
	}
	/**
	 * 在提交订单页中，显示购物车中的商品信息
	 * @param req
	 * @param res
	 * @param m
	 * @return
	 */
	@RequestMapping("/saveAddr")
	public String saveAddr(Addr a, HttpServletRequest req, HttpServletResponse res,Model m){
		
		
		UserY userY=(UserY) req.getSession().getAttribute("user");
		if (userY == null) {
			return "redirect:show.tq";
		}
		a.setUserid(userY.getUid());
		balanceServiceImpl.saveAddr(a);
		List<Addr> queryAddrByUid = balanceServiceImpl.queryAddrByUid(userY);
		m.addAttribute("addrs", queryAddrByUid);
		
		shopCarServiceImpl.queryCar(req, res, m);
		return "orderConfirm";
	}
	
	
	/**
	 * 校验购物车中所有商品的库存
	 * @param res
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/checkStockAll")
//	@ResponseBody
	public void checkStockAll(HttpServletRequest req,HttpServletResponse res) throws IOException{
		res.setCharacterEncoding("UTF-8");
		res.setContentType("text/plain;charset=UTF-8");
		PrintWriter out;
		out = res.getWriter();
		out.print(shopCarServiceImpl.checkStockAll(req));
		out.close();
	}
	
}
